#include "MyLog.h"
#pragma warning(disable: 4996) 

CMyLog::CMyLog(){}
CMyLog::CMyLog(const CMyLog &){}
CMyLog& CMyLog::operator = (const CMyLog &)
{
	return *pMyLog;
}


CMyLog* CMyLog::pMyLog = NULL;
CRITICAL_SECTION CMyLog::s_cs = {0};
FILE* CMyLog::fp = NULL; 

CMyLog* CMyLog::Instantialize(const char* szFileName)  
{  
#ifdef DEBUG_LOG
	if(NULL == pMyLog)  
	{  
 		::InitializeCriticalSection(&s_cs);
		pMyLog = new CMyLog();
		//
 		fp= fopen(szFileName,  "a+" ); 
 		if(fp == NULL) {
 			delete pMyLog;
 		}
	}  
	return pMyLog;  
#else 
	return NULL;
#endif
}  

void CMyLog::Destory()  
{  
#ifdef DEBUG_LOG
 	if(NULL != pMyLog)  
 	{  
		delete pMyLog;
 		fflush(fp);
 		fclose(fp);
 		fp = NULL;
		pMyLog = NULL;
		::DeleteCriticalSection(&s_cs);
 	}  
#else
	//nothing
#endif
}  

void  CMyLog::WriteLog(const char* szFileName, int line, const char* szFormat, ...)
{
	::EnterCriticalSection(&s_cs);
	__try{
		if(fp != NULL){
			time_t rawtime;
			struct tm * timeinfo;
			time ( &rawtime );
			timeinfo = localtime ( &rawtime );
			int year,month,day,hour,min,sec;
			year = 1900+timeinfo->tm_year;
			month = 1+timeinfo->tm_mon;
			day = timeinfo->tm_mday;
			hour = timeinfo->tm_hour;
			min = timeinfo->tm_min;
			sec = timeinfo->tm_sec;
			fprintf (fp, "[%4d/%02d/%02d-%02d:%02d:%02d-%s:%02d]:", year, month, day, hour, min, sec, szFileName, line);
			va_list arg_ptr;
			va_start(arg_ptr, szFormat);
			vfprintf(fp, szFormat,  arg_ptr);
			va_end(arg_ptr);
			fprintf(fp, "\n");
			fflush(fp);
		}
	}
	__except(1){
		::LeaveCriticalSection(&s_cs);
		return;
	}
	::LeaveCriticalSection(&s_cs);
}
